<!--
 * @Author       : xinbaiyu
 * @Version      : V1.0
 * @Date         : 2025-03-04 19:27:39
 * @Description  : 对话组件
-->
<template>
  <div
    ref="sessionBox"
    id="sessionBox"
    class="session-container"
    :class="{
      'session-container-small': smallScreen,
    }"
    :style="
      showAnswerDialog
        ? {}
        : {
            top: `${aiBot?.offsetTop || 0 + (aiBot?.clientHeight || 0 / 2)}px`,
            left: `${aiBot?.offsetLeft || 0 + (aiBot?.clientWidth || 0 / 2)}px`,
            width: 0,
            height: 0,
            boxShadow: 'none',
            margin: 'unset',
          }
    "
    @click="showSelect = false"
  >
    <div class="session-box">
      <div class="session-header">
        <h1 class="session-title">AI翻译助手</h1>
        <div class="operator-box">
          <el-button
            :icon="FullScreen"
            type="text"
            @click="smallScreen = !smallScreen"
          ></el-button>
          <el-button
            class="close-btn"
            :icon="Close"
            type="text"
            @click="emit('closeSession')"
          ></el-button>
        </div>
      </div>
      <div class="session-content">
        <div class="talk-item-box" ref="talkItemBox">
          <TalkItem
            :talkItemDetail="item"
            v-for="(item, index) in talkArr"
            :key="index"
            :sessionBox="(sessionBox as HTMLDivElement)"
          ></TalkItem>
        </div>
        <div class="input-box">
          <el-input
            v-model="question"
            :autosize="{ minRows: 2, maxRows: 6 }"
            type="textarea"
            placeholder="和机器人聊天"
            resize="none"
            @keyup.enter.native="askQuestion"
          >
          </el-input>
          <div class="right-operator">
            <el-button
              type="text"
              :icon="Position"
              :disabled="!question.length"
              @click="askQuestion"
            ></el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import checkType from '../util/checkType'
import { sendMessage } from '@/message'
import { reactive, defineEmits, onMounted, watch, defineProps } from 'vue'
import { ElInput, ElButton, ElIcon, ElMessage } from 'element-plus'
import { Close, FullScreen, Position } from '@element-plus/icons-vue/global'
import TalkItem from './TalkItem.vue'

const emit = defineEmits(['closeSession'])
const { showAnswerDialog, aiBot } = defineProps<{
  showAnswerDialog: boolean
  aiBot: HTMLElement | undefined
}>()
const smallScreen = ref(true)
const talkItemBox = ref<HTMLDivElement>()
const sessionBox = ref<HTMLDivElement>()
const question = ref('')
const showSelect = ref(false)

onMounted(async () => {})
let talkArr = reactive([
  { type: 'ai', content: '你好，我是你的ai翻译助手' },
])
watch(talkArr, async () => {
  await nextTick()
  scrollBottom()
})
watch(
  () => showAnswerDialog,
  async () => {
    await nextTick()
    scrollBottom()
  }
)

/**
 * @Author       : xinbaiyu
 * @Date         : 2025-03-21 22:16:17
 * @Version      : 0.0.1
 * @Description  : 发送问题
 * @param         {*} event:
 * @return        {*}
 */
const askQuestion = async (event: KeyboardEvent | MouseEvent) => {
  // 检查是否同时按下了Shift键和Enter键
  if (event?.shiftKey && (event as KeyboardEvent).key === 'Enter') {
    return
  }
  let questionStr = question.value
  // 输入不能为空
  if (!questionStr) {
    ElMessage({
      message: '输入不能为空！',
      appendTo: sessionBox.value as HTMLDivElement,
      type: 'error',
    })
    return
  }
  const config = await storage.getItem<RuleForm>('local:settings')
  // 配置不能不存在
  if (!config) {
    ElMessage({
      message: '请先配置api地址',
      appendTo: sessionBox.value as HTMLDivElement,
      type: 'error',
    })
    return
  }
  question.value = ''
  talkArr.push({ type: 'user', content: questionStr })
  let aiAnswer = reactive({ type: 'ai', content: '' })
  talkArr.push(aiAnswer)

  const response = await sendMessage('askAi', {
    text: questionStr,
    config: config as RuleForm,
  })
  console.log(response);
  
  aiAnswer.content = response?.message?.content || '系统错误请稍后重试'
}
/**
 * @Author       : xinbaiyu
 * @Date         : 2025-03-21 22:15:13
 * @Version      : 0.0.1
 * @Description  : 对话框滚动至底部
 * @return        {*}
 */
const scrollBottom = () => {
  const scrollBox = talkItemBox
  scrollBox.value!.scrollTop = scrollBox.value!.scrollHeight
}

defineExpose({
  question,
})
</script>

<style scoped lang="less"></style>
